package com.gok.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.gok.server.pojo.User;
import com.gok.service.UserService;
import com.gok.util.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author: Administrator
 * @create time: 2020/12/21 20:42
 * @description: 用户相关处理的控制器
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;


    @Autowired
    Result result;

    //处理用户的注册
    @RequestMapping("/register.do")
    @ResponseBody
    public String register(User user){
        //


        return "";
    }


    //处理用户的登录
    @RequestMapping("/login.do")
    @ResponseBody
    public String login(User user){
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());

        Subject subject= SecurityUtils.getSubject();
        //更新result，避免登录后result修改为20000(单例模式)
        result.setRespCode("-20000");

        //如果用户未认证
        if (!subject.isAuthenticated()){
            UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),user.getPassword());

            try{
                //认证
                subject.login(token);
                result.setRespCode("20000");
            }catch (UnknownAccountException uae) {//未知用户，用户名不存在
                result.setMsg("用户不存在");

            }catch (IncorrectCredentialsException ice) {//密码不正确
                result.setMsg("密码不正确");
            }finally {
                return JSONObject.toJSONString(result);
            }
        }
        result.setRespCode("20000");
        result.setMsg("认证成功");
        return JSONObject.toJSONString(result);
    }


    //处理用户的登出
    @RequestMapping("/logout.do")
    @ResponseBody
    public String login(){
        Subject subject= SecurityUtils.getSubject();

        try{
            subject.logout();
            result.setRespCode("20000");
            return JSONObject.toJSONString(result);
        }
        catch (Exception e){
            result.setRespCode("-20000");
            result.setMsg("登出失败");
            e.printStackTrace();
            return JSONObject.toJSONString(result);
        }
    }


    //到系统主页
    @RequestMapping("/toIndex.do")
    public String toIndex(){
        return "index";
    }
}
